package com.itheima.backend.filter;

import com.itheima.backend.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

//    @Override
//    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
//            throws ServletException, IOException {
//        // 登录接口放行
//        String url = request.getRequestURI();
//        if (url.contains("/login")) {
//            filterChain.doFilter(request, response);
//            return;
//        }
//        if(url.contains("/register")) {
//            filterChain.doFilter(request, response);
//            return;
//        }
//
//        // 获取并验证 JWT
//        String token = request.getHeader("Authorization");
//        if (token == null || !token.startsWith("Bearer ")) {
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            response.getWriter().write("Missing or invalid token");
//            return;
//        }
//
//        try {
//            token = token.replace("Bearer ", "");
//            Claims claims = JwtUtil.validateToken(token);
//            request.setAttribute("username", claims.getSubject());
//        } catch (Exception e) {
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            response.getWriter().write("Invalid token");
//            return;
//        }
//
//        // 放行其他请求
//        filterChain.doFilter(request, response);
//    }
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    // 添加安全响应头
    response.setHeader("X-Content-Type-Options", "nosniff");
    // 添加 CORS 响应头
    response.setHeader("Access-Control-Allow-Origin", "*"); // 或指定具体域名
    response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    // 登录接口放行
    String url = request.getRequestURI();
    if (url.contains("/login") || url.contains("/register")) {
        filterChain.doFilter(request, response);
        return;
    }

    // 获取并验证 JWT
    String token = request.getHeader("Authorization");
    if (token == null || !token.startsWith("Bearer ")) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("Missing or invalid token");
        return;
    }

    try {
        token = token.replace("Bearer ", "");
        Claims claims = JwtUtil.validateToken(token);
        request.setAttribute("username", claims.getSubject());
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("Invalid token");
        return;
    }

    // 放行其他请求
    filterChain.doFilter(request, response);
}

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        // 忽略预检请求
        return "OPTIONS".equalsIgnoreCase(request.getMethod());
    }

}
